package crawler.admin.controller;

import crawler.common.CommonUtil;
import crawler.common.PostData;
import crawler.common.RenderModel;
import crawler.common.UserRole;
import crawler.model.CNewsModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

public class AdminCNewsController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminCNewsController.class);
    private static final DateFormat formatter = new SimpleDateFormat("dd-MM-YYYY HH:mm");
    private static final int POST_PER_PAGE = 20;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminCNewsController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-delete-multiple":
                content = ajaxDeleteMultiple(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST)) {
                resp.sendRedirect("/post");
                return "";
            }
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "cnews"));
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");

            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }

            CNewsModel cNewsModel = CNewsModel.getInstance();
            List<PostData> lstCNews = cNewsModel.getPost((page - 1) * POST_PER_PAGE, POST_PER_PAGE);
            if (lstCNews != null) {
                for (PostData postData : lstCNews) {
                    TemplateDataDictionary section = dic.addSection("LIST_POST");
                    section.setVariable("POST_ID", String.valueOf(postData.getId()));
                    String site = postData.getSite();
                    if(site.startsWith("kenh14.vn")){
                        site = "Kenh14";
                    }else if(site.startsWith("ione.vnexpress.net")){
                        site = "IOne";
                    }else if(site.startsWith("ngoisao.net")){
                        site = "NgoiSao";
                    }
                    section.setVariable("POST_SITE", site);
                    section.setVariable("POST_URL", postData.getUrl());
                    section.setVariable("POST_CATEGORY", postData.getCategory());
                    section.setVariable("POST_THUMB", postData.getThumb());
                    section.setVariable("POST_THUMB_FB", postData.getThumbFb());
                    section.setVariable("POST_TITLE", postData.getTitle());
                    section.setVariable("POST_DESC", postData.getDesc());
                    section.setVariable("POST_CONTENT", postData.getContent());
                    section.setVariable("POST_TAGS", postData.getTags());
                    section.setVariable("POST_JOURNALIST", postData.getJournalist());
                    String published = formatter.format(postData.getPublished() * 1000L);
                    section.setVariable("POST_PUBLISHED", published);
                }
            }
            int count = (int) cNewsModel.getPostCount("1");
            String pageNavi = CommonUtil.getPageNavi(page, count, POST_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);

            Template template = RenderModel.getAdminCTemplate("post_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminCNewsController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }
    private String ajaxDeleteMultiple(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá Post thành công.";
        try {
            String ids = req.getParameter("ids") != null ? req.getParameter("ids") : "";
            if (ids.isEmpty()) {
                msg = "Post Id không được trống.";
                error = -1;
            } else {
                JSONParser parser = new JSONParser();
                JSONArray arr = (JSONArray) parser.parse(ids);
                CNewsModel cNewsModel = CNewsModel.getInstance();
                for (Object item : arr) {
                    String str = (String) item;
                    boolean delPost = cNewsModel.deletePost(str);
                    if (!delPost) {
                        msg = "Có lỗi xảy ra.";
                        error = -1;
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }
}
